import Vue from 'vue'
import axios from 'axios'


class THhKmsConfig {
    constructor() {
        this.systemFlag = "hhuRtc.v2022";
        //this.apiUrl = "http://wss.hhdata.cn:20040";
        //this.apiUrl = "http://localhost:20040";
        this.apiUrl = "https://dq.hhdata.cn:31020";
        this.db = {
            dbKey: "cock"
        };
        this.peerOptions = {
            configuration: {
                "iceServers": [{
                        //urls: "stun:39.171.53.53:3478"
                        urls: "stun:39.171.39.247:3478"
                            //urls: "stun:223.68.161.139:3478"
                            //urls: "stun:223.112.194.253:40016"
                    },
                    {
                        //urls: ["turn:39.171.53.53:3478"],
                        urls: ["turn:39.171.39.247:3478"],
                        //urls: ["turn:223.68.161.139:3478"],
                        //urls: ["turn:223.112.194.253:40016"],
                        username: "kurento",
                        credential: "kurento"
                    }
                ]
            },
            mediaConstraints: {
                audio: true,
                video: {
                    width: { min: 1280, ideal: 1920, max: 1920 },
                    height: { min: 720, ideal: 1080, max: 1080 }
                },
            }
        };
        this.peerFactories = {
            s: kurentoUtils.WebRtcPeer.WebRtcPeerSendonly,
            r: kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly,
            sr: kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv
        };
        this.kms = {
            tagKey: "tyagKey.kmsV2020-1",
            //kmsUrl: "wss://wj.hhdata.cn:10104/kurento",
            kmsUrl: "wss://dq.hhdata.cn:31003/kurento",
            //kmsUrl: "ws://dq.hhdata.cn:31008/kurento",
            //kmsUrl: "ws://wss.hhdata.cn:8888/kurento"
        };
    }
};
class THhKmsApi {
    constructor() {
        this.config = new THhKmsConfig();
    }
    callApi(apiPath, ps, method) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var url = [me.config.apiUrl, apiPath].join('/');

                var data = (ps && ps != null) ? ps : {};
                if (method == "GET") {
                    axios.get(url, data).then(res => {
                        success(res);
                    })
                } else {
                    axios.post(url, data).then(res => {
                        success(res);
                    })
                }
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    query(key, ps) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = "common/mysqldb/query";
                var postPs = {
                    appId: me.config.db.dbKey,
                    key: key,
                    psJson: JSON.stringify(ps)
                }
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data.data.result;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                })
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
}
class THhKmsConnection {
    constructor(_api) {
        this.api = _api;
        this.kmsClient = null;
        this.clientId = ['hc', (new Date()).getTime(), parseInt(1000 * Math.random())].join("");
    };
    getKmsClient() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (me.kmsClient && me.kmsClient != null) {
                    success(me.kmsClient);
                } else {
                    kurentoClient(me.api.config.kms.kmsUrl, function(error, _client) {
                        me.kmsClient = _client;
                        if (error) {
                            console.log(error);
                            success(null)
                        } else {
                            _client.on('disconnect', function() {
                                delete me['kmsClient'];
                            })
                            _client.getServerManager().then(_svr => {
                                me.kmsSvr = _svr;
                                //    return me.loadChannels();
                                //}).then(_chs => {
                                success(_client);
                            })

                        }
                    });
                }
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    getKmsObjs() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "kms", "getKmsObjs"].join("/");
                var postPs = {};
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    getChannels() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "channel", "getChannels"].join("/");
                var postPs = {};
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    createChannel(channelCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "channel", "createChannel"].join("/");
                var postPs = { channelCode: channelCode };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    closeChannel(channelCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "channel", "closeChannel"].join("/");
                var postPs = { channelCode: channelCode };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    getChannelInfo(channelCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "channel", "getChannelInfo"].join("/");
                var postPs = { channelCode: channelCode };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    getChannelSeats(channelCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "seat", "getChannelSeats"].join("/");
                var postPs = { channelCode: channelCode };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data.data.seats;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    createSeat(channelCode, seatCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "seat", "createSeat"].join("/");
                var postPs = {
                    channelCode: channelCode,
                    seatCode: seatCode
                };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    closeSeat(channelCode, seatCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "seat", "closeSeat"].join("/");
                var postPs = {
                    channelCode: channelCode,
                    seatCode: seatCode
                };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    getChannelEnds(channelCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "end", "getChannelEnds"].join("/");
                var postPs = {
                    channelCode: channelCode,
                    seatCode: seatCode
                };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    freeChannelEnds(channelCode, endIds) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "end", "freeChannelEnds"].join("/");
                var postPs = {
                    channelCode: channelCode,
                    endIds: endIds
                };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    freeEndsByClientId(channelCode, clientId) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var apiPath = ["hhKms", "end", "freeEndsByClientId"].join("/");
                var postPs = {
                    channelCode: channelCode,
                    clientId: clientId
                };
                me.api.callApi(apiPath, postPs, "POST").then(res => {
                    var result = null;
                    try {
                        result = res.data;
                    } catch (eer) {
                        result = null;
                    }
                    success(result);
                });

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    createKmsPeer(peerCode, peerType, video, channelCode, deviceId) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var client = null;
                var pipe = null;
                var peer = null;
                var end = null;
                var getPipe = () => {
                    return new Promise((su, fa) => {
                        me.getKmsClient().then(_client => {
                            client = _client;
                            return me.getChannelInfo(channelCode);
                        }).then(ch => {
                            if (ch && ch != null) {
                                client.getMediaobjectById(ch.id, function(erPipe, _pipe) {
                                    pipe = _pipe
                                    su();
                                });
                            } else {
                                su();
                            }
                        })
                    });
                };
                var newPeer = () => {
                    return new Promise((su, fa) => {
                        THhKmsConnection.createPeer(peerType, video, video, me.api.config.peerOptions, deviceId).then(_peer => {
                            peer = _peer;
                            su();
                        })
                    });
                };
                var newEnd = () => {
                    return new Promise((su, fa) => {
                        pipe.create("WebRtcEndpoint").then(_end => {
                            end = _end;
                            var info = {
                                type: 'peerEnd',
                                channelCode: channelCode,
                                clientId: me.clientId,
                                peerCode: peerCode,
                                peerType: peerType,
                                objName: peerCode,
                                id: _end.id,
                                kmsType: "WebRtcEndpoint",
                                flag: true
                            };
                            _end.info = info;
                            return _end.addTag(me.api.config.kms.tagKey, JSON.stringify(info));
                        }).then(_ => {
                            su();
                        })
                    });
                };
                var getVideo = () => {
                    var res = null;
                    try {
                        if (video && video != null) {
                            res = video;
                        } else {
                            var videoId = peerType == 's' ? 'lv' : 'rv';
                            videoId += "-" + peerCode;
                            var _v = document.getElementById(videoId);
                            if (_v && _v != null) {
                                res = _v;
                            } else {
                                res = THhKmsConnection.createVideo(videoId);
                            }
                        }
                    } catch (eer) {
                        console.log(eer);
                    }
                    return res;
                }
                getPipe().then(_ => {
                    if (pipe && pipe != null) {
                        newPeer().then(_ => {
                            return newEnd();
                        }).then(_ => {
                            return THhKmsConnection.bindPeerEnd(peer, end);
                        }).then(_ => {
                            var peerVideo = getVideo();
                            var kmsPeer = new THhKmsPeer(me, peerCode, peerType, peerVideo);
                            kmsPeer.channelCode = channelCode;
                            kmsPeer.pipe = pipe;
                            kmsPeer.end = end;
                            kmsPeer.peer = peer;
                            kmsPeer.video = peerVideo;
                            success(kmsPeer);
                        })
                    } else {
                        success();
                    }
                })
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    static bindPeerEnd(peer, endpoint) {
        return new Promise((success, faild) => {
            try {
                var setCandidateEvent = function(peer, endpoint) {
                    try {
                        if (peer && endpoint) {
                            endpoint.on('OnIceCandidate', function(event) {
                                var candidate = event.candidate;
                                peer.addIceCandidate(candidate);
                                //console.log(candidate);
                                console.log('candidate w->p', candidate);
                                //window.alert(JSON.stringify(candidate));
                            });
                            peer.on('icecandidate', function(candidate) {
                                var iceCandidate = kurentoClient.register.complexTypes.IceCandidate(candidate);
                                endpoint.addIceCandidate(iceCandidate);
                                //console.log(iceCandidate);
                                console.log('candidate p->w', iceCandidate);

                            });
                        }
                    } catch (e) {
                        console.log(e);
                    }
                }
                if (endpoint && peer) {
                    peer.generateOffer(function(errorPeerGenerateOffer, sdpOffer) {
                        if (errorPeerGenerateOffer) {
                            success();
                        } else {
                            endpoint.processOffer(sdpOffer, function(errorSdpOffer, sdpAnswer) {
                                if (errorSdpOffer) {
                                    console.log("process sdpOffer error.", errorSdpOffer)
                                    success()
                                } else {
                                    setCandidateEvent(peer, endpoint);
                                    peer.processAnswer(sdpAnswer, function(errorProccessAnswer) {
                                        endpoint.gatherCandidates(function(errorGatherCandidates) {
                                            if (errorGatherCandidates) {
                                                console.log('webRtcPoint gatherCandidates error.', errorGatherCandidates)
                                                success();
                                            } else {
                                                peer.endpoint = endpoint;
                                                endpoint.peer = peer;
                                                //setCandidateEvent(peer, endpoint);
                                                success();
                                            }
                                        });

                                    });
                                }
                            });
                        }
                    });
                } else {
                    success();
                }
            } catch (er) {
                console.log(er);
                success()
            }
        })
    }
    static createVideo(videoId) {
        var v = document.createElement('video');
        try {
            var style = 'width: 10px;height: 10px;left:-100px; top: -100px; position: absolute';
            v.id = (videoId && videoId != null && videoId != '') ? videoId : ['video', (new Date()).getTime, parseInt(1000 * Math.random())].join('_');
            v.setAttribute('style', style);
            document.body.append(v);
        } catch (er) {
            console.log(er);
            success();
        }
        return v;
    };
    static closePeer(peer) {
        return new Promise((success, faild) => {
            try {
                if (peer.peerConnection && peer.peerConnection != null && peer.peerConnection.localStream && peer.peerConnection.localStream != null) {
                    peer.peerConnection.localStream.stop();
                }
                if (peer.peerConnection && peer.peerConnection != null) {
                    peer.peerConnection.close();
                    peer.peerConnection.dispose();
                }
            } catch (er) {
                console.log(er);
                success();
            }
        })
    }
    static createPeer(peerType, localVideo, remoteVideo, peerOptions, deviceId) {
        return new Promise((success, faild) => {
            try {
                var peerFactories = {
                    s: kurentoUtils.WebRtcPeer.WebRtcPeerSendonly,
                    r: kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly,
                    sr: kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv
                };
                var lv = (localVideo && localVideo != null) ? localVideo : THhuRtc.createVideo();
                var rv = (remoteVideo && remoteVideo != null) ? remoteVideo : THhuRtc.createVideo();
                var factory = peerFactories[peerType];
                var opts = JSON.parse(JSON.stringify(peerOptions));
                if (peerType == 's') {
                    opts.localVideo = lv;
                } else if (peerType == 'r') {
                    opts.remoteVideo = rv;
                } else if (peerType == 'sr') {
                    opts.localVideo = lv;
                    opts.remoteVideo = rv;
                }
                if ((peerType == 's' || peerType == 'sr') && deviceId && deviceId != "") {
                    opts.mediaConstraints.video.deviceId = deviceId;
                }
                var wrPeer = factory(opts, function(erP) {
                    console.log(erP);
                    wrPeer.peerOption = opts;
                    success(wrPeer);
                });
            } catch (er) {
                console.log(er);
                success();
            }
        })
    };
    static shareScreen(peer, width, height) {
        return new Promise((success, faild) => {
            try {
                var wWidth = width && width > 0 ? width : (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
                var wHeight = height && height > 0 ? height : (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
                var screenConstraints = { video: { width: { max: wWidth }, height: { max: wHeight } }, audio: true };
                var sender = null;
                if (navigator.mediaDevices.getDisplayMedia) {
                    navigator.mediaDevices.getDisplayMedia(screenConstraints).then(
                        function(stream) {
                            let videoTrack = stream.getVideoTracks()[0];
                            peer.localVideo.srcObject = stream;
                            sender = peer.peerConnection.getSenders().find(function(s) {
                                return s.track.kind == videoTrack.kind;
                            });
                            sender.track.stop();
                            sender.replaceTrack(videoTrack);
                            success();
                        }
                    )
                } else {
                    success();
                }
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    static fullScreen(peer) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var element = peer.remoteVideo;
                me.fullScreenElement(element).then(_ => {
                    success();
                })
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    static fullScreenElement(element) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                }
                success();
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    static setCamera(peer, newDeviceId) {
        return new Promise((success, faild) => {
            try {
                var currentDeviceId = peer.getLocalStream().getVideoTracks()[0].getSettings().deviceId;
                if (currentDeviceId != newDeviceId) {
                    var stream = peer.getLocalStream();
                    stream.getTracks().forEach(t => {
                        t.stop();
                    });
                }
                var mediaConstraints = peer.peerOption.mediaConstraints;
                mediaConstraints.video.deviceId = newDeviceId;
                navigator.mediaDevices.getUserMedia(mediaConstraints).then(function(stream) {
                    try {
                        peer.localVideo.srcObject = stream;
                        var streamTracks = {};
                        stream.getTracks().forEach(st => {
                            try {
                                streamTracks[st.kind] = st;
                            } catch (eer) {
                                console.log(eer);
                            }
                        });
                        peer.peerConnection.getSenders().forEach(_sender => {
                            try {
                                var kind = _sender.track.kind;
                                _sender.track.stop();
                                var stTrack = streamTracks[kind];
                                _sender.replaceTrack(stTrack);
                            } catch (eer) {
                                console.log(eer);
                            }
                        });
                    } catch (eSet) {
                        console.log(eSet);
                    }
                    try {
                        success();
                    } catch (eer) {
                        console.log(eer);
                    }
                }).catch(function(erSet) {
                    console.log(erSet);
                    try {
                        success();
                    } catch (eer) {
                        console.log(eer);
                    }
                });

            } catch (er) {
                console.log(er);
                try {
                    success();
                } catch (eer) {
                    console.log(eer);
                }
            }
        });
    };
    getDevices() {
        var res = {};
        return new Promise((success, faild) => {
            try {
                navigator.mediaDevices.enumerateDevices().then(function(devs) {
                    try {
                        for (var i = 0; i < devs.length; i++) {
                            var item = devs[i];
                            if (!res[item.kind]) {
                                res[item.kind] = []
                            }
                            res[item.kind].push(item);
                        }
                    } catch (er) {
                        console.log(er);
                    }
                    success(res);
                }).catch(function() {
                    success(res);
                });
            } catch (er) {
                console.log(er);
                success(res);
            }
        });
    };
};
class THhKmsPeer {
    constructor(_connection, _peerCode, _peerType, _video) {
        this.connection = _connection;
        this.peerCode = _peerCode;
        this.channelCode = "";
        this.currentSeatCode = "";
        this.peerType = _peerType;
        this.video = _video;
        this.peer = null;
        this.end = null;
    };

    open(seatCode) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                me.connection.getChannelSeats(me.channelCode).then(seats => {
                    var arr = seats.filter(s => {
                        return s.seatCode == seatCode;
                    });
                    if (arr.length > 0) {
                        var ptId = arr[0].id;
                        me.connection.getKmsClient().then(_client => {
                            return _client.getMediaobjectById(ptId)
                        }).then(pt => {
                            var src = me.peerType == 's' ? me.end : pt;
                            var target = me.peerType == 's' ? pt : me.end;
                            return src.connect(target);
                        }).then(_connectStatus => {
                            console.log('connect', _connectStatus);
                            me.currentSeatCode = seatCode;
                            success({
                                status: _connectStatus && _connectStatus != null ? _connectStatus : 'ok'
                            });
                        });
                    } else {
                        success();
                    }
                })
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    setCamera(cameraDeviceId) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (me.peerType == 's' || me.peerType == 'sr') {
                    THhKmsConnection.setCamera(me.peer, cameraDeviceId).then(_ => {
                        success();
                    })
                } else {
                    success();
                }
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    shareScreen() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (me.peerType == 's' || me.peerType == 'sr') {
                    THhKmsConnection.shareScreen(me.peer).then(_ => {
                        success();
                    })
                } else {
                    success();
                }
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
};

class THhKmsModel {
    constructor(_connection) {
        this.settings = {
            channelCode: "hhKmsClient",
            seats: [
                { seatCode: "s01", title: "1#坐席" },
                { seatCode: "s02", title: "2#坐席" },
                { seatCode: "s03", title: "3#坐席" },
                { seatCode: "s04", title: "4#坐席" }
            ],
            pushers: [
                { code: "localCamera", title: "本地摄像头", defaultSeatCode: "s01", deviceId: "", video: null },
                { code: "mobileCamera", title: "移动摄像头", defaultSeatCode: "s01", deviceId: "", video: null }
            ],
            pullers: [
                { code: "p01", seatCode: "s01", title: "1#坐席", video: null },
                { code: "p02", seatCode: "s02", title: "2#坐席", video: null },
                { code: "p03", seatCode: "s03", title: "3#坐席", video: null },
                { code: "p04", seatCode: "s04", title: "4#坐席", video: null }
            ],
        };
        this.connection = _connection && _connection != null ? _connection : new THhKmsConnection(new THhKmsApi());
        this.channelPipe = null;
        this.channelInfo = {};
        this.seats = {};
        this.pushers = {};
        this.pullers = {};
        this.devices = [];
    };
    init() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                me.connection.getDevices().then(devs => {
                    me.devices = devs.videoinput;
                    success();
                });
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    open() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                // set pushers video
                var settings = JSON.parse(JSON.stringify(me.settings));
                var loadChannel = () => {
                    return new Promise((su, fa) => {
                        try {
                            me.connection.createChannel(settings.channelCode).then(chInfo => {
                                me.channelInfo = chInfo;
                                return me.connection.getKmsClient();
                            }).then(_client => {
                                return _client.getMediaobjectById(me.channelInfo.id);
                            }).then(_pipe => {
                                me.channelPipe = _pipe;
                                return me.connection.getChannelSeats(me.settings.channelCode);
                            }).then(_seats => {
                                var seats = {};
                                _seats.forEach(s => {
                                    seats[s.seatCode] = s;
                                });
                                me.seats = seats;
                                var index = 0;
                                var loadSeats = () => {
                                    if (index < settings.seats.length) {
                                        var seatItem = settings.seats[index];
                                        if (seats[seatItem.code] && seats[seatItem.code] != null) {
                                            index++;
                                            loadSeats();
                                        } else {
                                            me.connection.createSeat(me.settings.channelCode, seatItem.seatCode).then(_ => {
                                                index++;
                                                loadSeats();
                                            })
                                        }
                                    } else {
                                        me.connection.getChannelSeats(me.settings.channelCode).then(chSeats => {
                                            var _chseats = {};
                                            chSeats.forEach(s => {
                                                _chseats[s.seatCode] = s;
                                            });
                                            me.seats = _chseats;
                                            su();
                                        });
                                    }
                                }
                                loadSeats();
                            })
                        } catch (err) { console.log(err) };
                    });
                };
                var getVideo = (video, videoId) => {
                    var res = null;
                    try {
                        if (video && video != null) {
                            res = video;
                        } else {
                            var _v = document.getElementById(videoId);
                            if (_v && _v != null) {
                                res = _v;
                            } else {
                                res = THhKmsConnection.createVideo(videoId);
                            }
                        }
                    } catch (err) { console.log(eer) };
                    return res;
                };
                var loadPushers = () => {
                    return new Promise((su, fa) => {
                        try {
                            var index = 0;
                            var loadItem = () => {
                                if (index < settings.pushers.length) {
                                    var pusher = settings.pushers[index];
                                    me.pushers[pusher.code] = pusher;
                                    var videoId = pusher.videoId && pusher.videoId != null && pusher.videoId.length > 0 ? pusher.videoId : ["lv", pusher.code].join("-");
                                    var peerVideo = getVideo(pusher.video, videoId)
                                    me.connection.createKmsPeer(pusher.code, 's', peerVideo, settings.channelCode, pusher.deviceId).then(_kmsPeer => {
                                        pusher.kmsPeer = _kmsPeer;
                                        var flag = pusher.defaultSeatCode && pusher.defaultSeatCode != '' &&
                                            me.seats[pusher.defaultSeatCode] && me.seats[pusher.defaultSeatCode] != null;
                                        if (flag) {
                                            pusher.kmsPeer.open(pusher.defaultSeatCode).then(_ => {
                                                index++;
                                                loadItem();
                                            })
                                        } else {
                                            index++;
                                            loadItem();
                                        }
                                    });
                                } else {
                                    su();
                                }
                            };
                            loadItem();
                        } catch (err) { console.log(err) };
                    });
                };
                var loadPullers = () => {
                    return new Promise((su, fa) => {
                        try {
                            var index = 0;
                            var loadItem = () => {
                                if (index < settings.pullers.length) {
                                    var puller = settings.pullers[index];
                                    me.pullers[puller.code] = puller;
                                    var videoId = puller.videoId && puller.videoId != null && puller.videoId.length > 0 ? puller.videoId : ["rv", puller.code].join("-");
                                    var peerVideo = getVideo(puller.video, videoId)
                                    me.connection.createKmsPeer(puller.code, 'r', peerVideo, settings.channelCode).then(_kmsPeer => {
                                        puller.kmsPeer = _kmsPeer;
                                        var flag = puller.defaultSeatCode && puller.defaultSeatCode != '' &&
                                            me.seats[puller.defaultSeatCode] && me.seats[puller.defaultSeatCode] != null;
                                        if (flag) {
                                            puller.kmsPeer.open(puller.defaultSeatCode).then(_ => {
                                                index++;
                                                loadItem();
                                            })
                                        } else {
                                            index++;
                                            loadItem();
                                        }
                                    });
                                } else {
                                    su();
                                }
                            };
                            loadItem();
                        } catch (err) { console.log(eer) };
                    });
                };
                loadChannel().then(_ => {
                    return loadPushers();
                }).then(_ => {
                    return loadPullers();
                }).then(_ => {
                    success();
                })
            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    openPusher(obj) {
        var me = this;
        return new Promise((success, faild) => {
            try {

            } catch (er) {
                console.log(er);
                success();
            }
        });
    };
    openPuller(obj) {
        var me = this;
        return new Promise((success, faild) => {
            try {} catch (er) {
                console.log(er);
                success();
            }
        });
    };
    closeSelf() {
        var me = this;
        var me = this;
        return new Promise((success, faild) => {
            try {} catch (er) {
                console.log(er);
                success();
            }
        });
    };
    closeChannel() {
        var me = this;
        var me = this;
        return new Promise((success, faild) => {
            try {} catch (er) {
                console.log(er);
                success();
            }
        });
    };
};


export {
    THhKmsConfig,
    THhKmsApi,
    THhKmsConnection,
    THhKmsPeer,
    THhKmsModel
};